package com.contract.spirit.ui.main.my

import android.app.Activity
import android.view.View
import cn.woochen.comlib.util.ConfigPref
import cn.woochen.comlib.util.UserPref
import com.contract.commonlib.util.ext.setOnSingleClickListener
import com.contract.commonlib.http.https.CertificateManageHelper
import com.contract.commonlib.application.ApplicationProxy
import com.contract.commonlib.base.BaseFragment
import com.contract.commonlib.config.Constants
import com.contract.commonlib.dialog.CommonDialog
import com.contract.commonlib.http.RetrofitUtil
import com.contract.commonlib.http.ext.parseState
import com.contract.commonlib.refresh.IRefreshCallBack
import com.contract.commonlib.refresh.RefreshManager
import com.contract.commonlib.util.RecycleviewLayoutManger
import com.contract.commonlib.util.ext.gsonToJson
import com.contract.commonlib.util.ext.showToast
import com.contract.spirit.BuildConfig
import com.contract.spirit.R
import com.contract.spirit.bean.entity.MenuInfo
import com.contract.spirit.bean.entity.User
import com.contract.spirit.config.MenuConfig
import com.contract.spirit.databinding.FrgMainMyBinding
import com.contract.spirit.manage.CommonConfigManager
import com.contract.spirit.manage.LiveDataEventManager
import com.contract.spirit.ui.UserViewModel
import com.contract.spirit.ui.exchange.ExchangeOrderSelectActivity
import com.contract.spirit.ui.income.IncomeDetailsActivity
import com.contract.spirit.ui.invite.InviteActivity
import com.contract.spirit.ui.invite.MyInviteUserActivity
import com.contract.spirit.ui.login.LoginActivity
import com.contract.spirit.ui.password.SetPasswordActivity
import com.contract.spirit.ui.system.AboutActivity
import com.contract.spirit.ui.system.CustomServiceActivity
import com.jeremyliao.liveeventbus.LiveEventBus

/**
 * @author: witness
 * created: 2021/9/17
 * desc:
 */
class MainMyFrg : BaseFragment<FrgMainMyBinding, UserViewModel>() {

    private val menuAdapter by lazy {
        MenuAdapter()
    }

    var user: User? = null

    override fun setContentView(): Int {
        return R.layout.frg_main_my
    }

    override fun initData() {
        CommonConfigManager
        mBinding.apply {
            ivExit.setOnSingleClickListener {
                showConfirmExitDialog()
            }
            vgIncome.setOnSingleClickListener {
                IncomeDetailsActivity.launch(mContext)
            }
        }
        initMenuRecycleview()
        setTestBtn()
        getUserInfo()
    }

    override fun onReload() {
        mViewModel.userResponse.value = null
        getUserInfo()
    }

    override fun initRefresh() {
        RefreshManager.getInstance()
            .initRefresh(mContext, null, false, mBinding.refreshLayout, object : IRefreshCallBack {
                override fun onRefresh() {
                    getUserInfo()
                }
            })
    }

    private var isTest by ConfigPref(Constants.IS_TEST, false)
    private fun setTestBtn() {
        mBinding.apply {
            if (BuildConfig.isRelease) {
                btnSwitch.visibility = View.GONE
            } else {
                if (isTest) {
                    btnSwitch.text = "切换到正式环境"
                } else {
                    btnSwitch.text = "切换到测试环境"
                }
                btnSwitch.visibility = View.VISIBLE
                btnSwitch.setOnClickListener {
                    showToast("请重新登录")
                    isTest = !isTest
                    UserPref.clear()
                    ApplicationProxy.instance?.getBaseUrl()?.let { it1 ->
                        RetrofitUtil.getInstance().init(it1, {
                            if (!BuildConfig.isRelease) {
                                it.sslSocketFactory(
                                    CertificateManageHelper.getSSLSocketFactory(),
                                    CertificateManageHelper.getTrustManager()
                                )
                                it.hostnameVerifier(CertificateManageHelper.getHostnameVerifier())
                            }
                        })
                    }
                    LoginActivity.launch(mContext)
                    (mContext as Activity).finish()
                }
            }
        }
    }

    private fun initMenuRecycleview() {
        RecycleviewLayoutManger.setVerticalManager(mBinding.rvMenu, mContext)
        menuAdapter.setList(MenuConfig.menuList)
        mBinding.rvMenu.adapter = menuAdapter
        setOnMenuItemClick()
    }

    private fun setOnMenuItemClick() {
        menuAdapter.setOnItemClickListener { _, _, position ->
            val menuInfo: MenuInfo = menuAdapter.getItem(position)
            when (menuInfo.type) {
                MenuConfig.TYPE_ORDER ->
                    //我的订单
                    ExchangeOrderSelectActivity.launch(mContext)
                MenuConfig.TYPE_INVITE ->
                    //邀请助力
                    InviteActivity.launch(mContext)
                MenuConfig.TYPE_GROUP ->
                    //我的团队
                    MyInviteUserActivity.launch(mContext)
                MenuConfig.TYPE_PASSWORD ->
                    //资金密码
                    SetPasswordActivity.launch(mContext)
                MenuConfig.TYPE_ABOUT->
                    //关于我们
                    AboutActivity.launch(mContext)
                MenuConfig.TYPE_SERVICE->
                    //我的客服
                    CustomServiceActivity.launch(mContext)
            }
        }
    }

    private fun getUserInfo() {
        mViewModel.getUserInfo()
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        onGetUserInfoObserve()
        onExitLoginObserve()
        onLiveDataEventsObserve()
    }

    private fun onExitLoginObserve() {
        mViewModel.exitResponse.observe(this, {
            parseState(it, {
                showToast("退出成功")
                UserPref.clear()
                LoginActivity.launch(mContext)
                (mContext as Activity).finish()
            })
        })
    }

    private fun onGetUserInfoObserve() {
        mViewModel.userResponse.observe(this, { it ->
            parseState(it, {
                user = it
                mBinding.user = it
                CommonConfigManager.userinfo = gsonToJson(user)
            })
            endRefreshing(mBinding.refreshLayout)
        })
    }

    private fun onLiveDataEventsObserve(){
        LiveEventBus.get<String>(LiveDataEventManager.GAIN_SUCCESS)
            .observe(this,{
                getUserInfo()
            })
        LiveEventBus.get<String>(LiveDataEventManager.WITHDRAW_SUCCESS)
            .observe(this,{
                getUserInfo()
            })
    }

    private val commonDialog by lazy {
        CommonDialog(mContext)
    }

    private fun showConfirmExitDialog() {
        commonDialog.setTitle("")
        commonDialog.setSubTitle("确定退出登录？")
        commonDialog.setCancelBtn("取消") { commonDialog.dismiss() }
        commonDialog.setConfirmBtn("确定") { exitLogin() }
        commonDialog.show()
    }

    private fun exitLogin() {
        commonDialog.dismiss()
        mViewModel.logOut()
    }
}